package mastermind.view.dialog;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;

import mastermind.Client;
import mastermind.DataOperator;
import mastermind.Client.MMLoginException;
import mastermind.controller.CancelListener;
import mastermind.game.Pieces;
import mastermind.view.ClientGUI;

/**
 * A dialog to allow user to login to MM server
 */
public class LoginDialog extends JDialog {
	private static final long serialVersionUID = 5337168160412213251L;
	private JComboBox username;
	private JPasswordField password;

	private ClientGUI cgui;
	private Client client;

	public LoginDialog(ClientGUI cgui) {
		this.cgui = cgui;
		this.client = cgui.getClient();
		
		setTitle("login");
		setLayout(new GridBagLayout());
		setModal(true);

		username = new JComboBox(getLocalUsers());
		username.setEditable(true);
		password = new JPasswordField(15);

		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.insets = new Insets(5, 5, 5, 5);
		c.weightx = 0.5;
		c.gridy = 0;

		c.gridy++;
		add(new JLabel("username"), c);
		add(username, c);

		c.gridy++;
		add(new JLabel("password"), c);
		add(password, c);

		JPanel buttons = new JPanel();
		JButton create = new JButton("login");
		create.addActionListener(new LoginListener());
		buttons.add(create);

		JButton cancel = new JButton("cancel");
		cancel.addActionListener(new CancelListener(this));
		buttons.add(cancel);

		c.gridy++;
		c.gridwidth = 2;
		add(buttons, c);

		pack();
		// center and display
		setLocationRelativeTo(null);
		setVisible(true);
	}

	public String getUsername() {
		return username.getSelectedItem().toString();
	}

	public String getPassword() {
		return new String(password.getPassword());
	}

	/**
	 * Returns those users who have registered using this client
	 * 
	 * @return Array of user names
	 */
	private String[] getLocalUsers() {
		ArrayList<String> users = new ArrayList<String>();
		File userlog = new File(DataOperator.LOCAL_LOG);
		// make sure the user log actually has been written
		if (userlog.exists()) {
			try {
				Scanner scanner = new Scanner(userlog);
				while (scanner.hasNextLine()) {
					users.add(scanner.nextLine());
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return users.toArray(new String[users.size()]);
	}
	
	/** Handles login with user entered details */ 
	class LoginListener implements ActionListener {

		public void actionPerformed(ActionEvent arg0) {
			if (getUsername().isEmpty()) {
				cgui.errorMessage("you must enter a username",
						"invalid username");
			}
			
			try {
				Map<Pieces, String> guesses = client.login(getUsername(),
						getPassword());
				cgui.setLoggedIn(true);
				cgui.setCurrentUser(getUsername());
				if(guesses != null) {
					cgui.restoreGame(guesses);
				}
			} catch (MMLoginException e) {
				cgui.errorMessage(e.getMessage(), "error logging in");
			}
			LoginDialog.this.dispose();
		}
	}
}
